/**
 * Created by kevin on 2017/01/08.
 *
 * page base
 */


var eosi = window.eosi || {};
this.eosi.website = this.eosi.website || {};

(function (window) {
    // the application


    function BasePage(config) {

        this.Container_constructor();
        this.config = config;
        //console.log(this.config)
        this.init();
        //console.log(this.father.targetWidth);

    }


    var p = createjs.extend(BasePage, createjs.Container);
    p.className = "BasePage";

    p.config;
    p.resIsLoaded = false;

    p.resItems=[];
    p.loader;
    p.isDraw = false;
    p.pageIndex=null;


    // public methods:
    p.init = function () {
        this.loadRes();//K
        this.on("removed",this.distoryPage,this);
    }

    /*
     * 加载资源
     * */
    p.loadRes = function(){
        this.resItems = [];
        this.loader = new createjs.LoadQueue(true);
        
        this.loader.on("fileload", this.onLoaded, this);
        this.loader.on("progress", this.onProgress, this);
        this.loader.on("complete", this.loadComplete, this);
        this.loader.on("error", this.onError, this);
        this.loader.loadManifest({src: this.config.src+"?v="+version, callback: this.config.callback, type: "manifest"}, true, "./");

    }
    /*
    加载失败
    */
    p.onError = function(evt){
        console.log(evt)
    }
    /*
     * 资源加载
     * */
    p.onLoaded = function (evt){
        // console.log(evt.currentTarget.getItems(),this.name);
        
        var item = evt.item;
        var result = evt.result;
        // console.log(result)
        // console.log(typeof(result))
        // if(typeof(result) == Object){
        //     console.log(result)
        // }
        this.resItems.push(item);
    }
    p.onProgress = function(evt){
        // console.log(evt);
        
        // if(LAND_PAGE){
        //     onProgress(evt);
        // }else{
            // onProgress(evt,CORE_RES_SIZE_PER,1-CORE_RES_SIZE_PER);
        // }

    }

    
    /*
     * 资源加载完毕
     * */
    p.loadComplete = function (evt){
        // console.log(this.resItems[0]);
        console.log(evt.target.getItems(),this.resItems,this.resItems.length)
        if(LAND_PAGE==null){
            LAND_PAGE = this;
        }
        this.resIsLoaded = true;
        this.config.resIsLoaded = this.resIsLoaded;
        //console.log(cur_page,this.name)
        if(!this.config.type=="pages"){
            this.drawPage();
        }else{
            this.drawPage();
        }
        

        onComplete(evt);
        if(!this.config.type=="pages"){
            contentLayer.preload(this.pageIndex);
        }

    }
    /*
    * 设置scale
    * */
    p.setScale = function(item,i){
        var pic = item;
        //console.log(pic)

        // this.loader.getResult(this.resItems[i].id);
        switch (this.resItems[i]["Pages"][this.name].prop.fit){
            case "fit_all"://强制全屏
                //item.setTransform(0,0,targetWidth/pic.getBounds().width,targetHeight/pic.getBounds().height);
                item.scaleX= targetWidth/pic.getBounds().width
                item.scaleY = targetHeight/pic.getBounds().height
                //console.log(item.scaleX)
                break;
            case "fit_screen"://根据屏幕比例适配，不变性(相对于屏幕的比例)
                item.regX = pic.getBounds().width*.5;
                item.regY = pic.getBounds().height*.5;
                var ratio = this.resItems[i]["Pages"][this.name].prop.scale*targetWidth/pic.getBounds().width;
                //item.setTransform(0,0,ratio,ratio);
                item.scaleX=item.scaleY= ratio;

                if(item.oriScale){
                    item.oriScale = ratio
                }
                break;
            default :
                break;
        }
    }

    /*
    * 设置中心点
    * */
    p.setInit = function(item,i){
        if(this.resItems[i]["Pages"][this.name].prop.initSet){//相对位置
            for (var j in this.resItems[i]["Pages"][this.name].prop.initSet ) {
                item[""+j]=this.resItems[i]["Pages"][this.name].prop.initSet[j];
                console.log("item."+j+"="+this.resItems[i]["Pages"][this.name].prop.initSet[j])
            }
        }
    }

    /*
    * 设置位置
    * */
    p.setPos = function(item,i){
        if(this.resItems[i]["Pages"][this.name].pos.type == "abs"){//绝对位置
            switch (this.resItems[i]["Pages"][this.name].prop.align){
                case "TL":
                    item.x = 0;
                    item.y = 0;
                    break;
                case "TR":
                    item.x = targetWidth;
                    item.y = 0;
                    break;
                case "TM":
                    item.x = targetWidth*0.5;
                    item.y = 0;
                    break;
                case "BL":
                    item.x = 0;
                    item.y = targetHeight;
                    break;
                case "BR":
                    item.x = targetWidth;
                    item.y = targetHeight;
                    break;
                case "BM":
                    item.x = targetWidth*.5;
                    item.y = targetHeight;
                    break;
                case "MM":
                    item.x = targetWidth*.5;
                    item.y = targetHeight*.5;
                    break;
                case "DB":
                    item.x = targetWidth*.5;
                    item.y = targetHeight-item.getBounds().height/2*item.scaleY;
                    break;
            }
            item.x += this.resItems[i]["Pages"][this.name].prop.offset.x * targetWidth;
            item.y += this.resItems[i]["Pages"][this.name].prop.offset.y * targetHeight;
        }else if(this.resItems[i]["Pages"][this.name].pos.type == "rel"){//相对位置
            var father = this.getChildByName(this.resItems[i]["Pages"][this.name].pos.father);
            var relWidth = targetWidth;
            var relHeight = targetHeight;
            //console.log(father)
            if(father){
                item.father = this.resItems[i]["Pages"][this.name].pos.father;
                item.x = father.x;
                item.y = father.y;
                relWidth = father.getBounds().width;
                relHeight = father.getBounds().height;
                //如果父亲也有动画，使用目标值作为参数的zhi
                // if(father.proObj!=undefined){
                //     // alert(1);
                //     //console.log(father.proObj)
                //     if(father.proObj.y !=undefined){
                //         item.y = father.proObj.y;
                //     }
                //     if(father.proObj.x !=undefined){
                //         item.y = father.proObj.x;
                //     }

                // }
            }
            console.log(item.x,item.y,relWidth,relHeight);
            item.x += this.resItems[i]["Pages"][this.name].prop.offset.x * relWidth;
            item.y += this.resItems[i]["Pages"][this.name].prop.offset.y * relHeight;
            console.log(item.x,item.y);
        }
    }

    /*
    * 设置action
    * */
    p.setAction = function(item,i){
        var action = this.resItems[i]["Pages"][this.name].action
        if( action != "none"){
            var hit = new createjs.Shape();
            hit.graphics.beginFill("#000").drawRect(0,0,item.getBounds().width,item.getBounds().height);  // opaque black 50x50 square
            item.hitArea = hit;
            item.on("click",this.onClickItem,this);
            switch (action.type){
                case "popup"://弹窗s
                    item.group_id = action.group_id;
                    break;
                case "jumpto"://跳转
                    item.page = action.page;
                    break;
                case "jumptoURL"://跳转外链
                    item.url = action.url;
                    break;
                case "triggerAnimation"://点击执行动画
                    item.id_list=action.id_list;
                    break;
                case "videoPlay"://点击执行动画
                    item.video_pro=action.video_pro;
                    break;
                case "show_html_pop":
                    item.show_html_id=action.show_html_id;
                    break;
                case "Assembly":
                    item.AssemblyName=action.AssemblyName;
                    break;
            }
            //window.location = "http://mywebsite.com/choose.php";

        }
    }
    /*
    * 设置animation
    * */
    p.setAnimation = function(item,i){
        var config = this.resItems[i]["Pages"][this.name].tween;
        if(config){
            var tween = createjs.Tween.get(item,{loop:config.loop});
            if(config.wait){
                tween.wait(config.wait);
            }
            item.proObj = {};//记住对象的最终属性
            item.conObj = {};//记住对象的初始属性
            for(var key in config.prop){
                item.proObj[key] = item[key];//将目标参数记录在obj 中
                if(key!="y" && key!="x"){
                    item.conObj[key] = item[key] = config.prop[key];//改变初始参数
                }else{
                    var relWidth = targetWidth;
                    var relHeight = targetHeight;
                    if (item.father) {
                        var father = this.getChildByName(item.father);
                        if(father){
                            relWidth = father.getBounds().width;
                            relHeight = father.getBounds().height;
                        }
                    }
                    if(key=="y"){
                        item.conObj[key] = item[key] = config.prop[key]*relHeight;
                    }else{
                        item.conObj[key] = item[key] = config.prop[key]*relWidth;
                    }
                }
            }
            // console.log(item.conObj,item.proObj)
            tween.to(item.proObj,config.during,createjs.Ease[config.ease]);
            if(config.loop){
                tween.to(item.conObj,config.during,createjs.Ease[config.ease]);
            }
            if(config.call){
                try{
                    tween.call(eval(config.call));
                }catch(e){
                    console.log(this.className+" no func '"+config.call+"'");
                }
            }
            if(this.resItems[i]["Pages"][this.name]["tween2"]){
                var that=this;
                tween.call(function(){
                    that.nextAnimation(item,that.resItems[i]["Pages"][that.name].tween2);
                });
            }
        }
    }

    p.nextAnimation=function(item,dm){
        var config = dm;
        var tween = createjs.Tween.get(item,{loop:config.loop});
        if(config.wait){
            tween.wait(config.wait);
        }
        item.proObj = {};//记住对象的最终属性
        item.conObj = {};//记住对象的初始属性
        for(var key in config.prop){
            item.conObj[key] = item[key];//将目标参数记录在obj 中
            if(key!="y" && key!="x"){
                item.proObj[key] = config.prop[key];//改变初始参数
            }else{
                var relWidth = targetWidth;
                var relHeight = targetHeight;
                if (item.father) {
                    var father = this.getChildByName(item.father);
                    if(father){
                        relWidth = father.getBounds().width;
                        relHeight = father.getBounds().height;
                    }
                }
                if(key=="y"){
                    item.proObj[key] = config.prop[key]*relHeight;
                }else{
                    item.proObj[key] = config.prop[key]*relWidth;
                }
            }
        }
        // console.log(item.conObj,item.proObj);
        tween.to(item.proObj,config.during,createjs.Ease[config.ease]);
        if(config.loop){
            tween.to(item.conObj,config.during,createjs.Ease[config.ease]);
        }
        if(config.call){
            try{
                tween.call(eval(config.call));
            }catch(e){
                console.log(this.className+" no func '"+config.call+"'");
            }
        }
    }

    /*
    * reset animation
    * 重放动画
    * */
    p.resetAnimation = function(){
        for(var i = 0 ;i<this.children.length;i++){
            //console.log(this.getChildAt(i));
            var item = this.getChildAt(i);
            this.setAnimation(item,item.resIndex);
        }
    }
    /*
    * trigger animation
    * 点击触发动画
    * */
    p.triggerAnimation = function (target_id) {
        var that = this;
        var item = this.getChildByName(target_id);
        if(item == null){
            return;
        }
        var config = item.tweenTrigger;
        if(config){
            var tween = createjs.Tween.get(item,{loop:config.loop});
            if(config.wait){
                tween.wait(config.wait);
            }
            item.proObj = {};//记住对象的最终属性
            item.conObj = {};//记住对象的初始属性
            for(var key in config.prop){
                item.conObj[key] = item[key];//将目标参数记录在obj 中
                if(key!="y" && key!="x"){
                    item.proObj[key] = config.prop[key];//改变初始参数
                }else{
                    var relWidth = targetWidth;
                    var relHeight = targetHeight;
                    if (item.father) {
                        var father = this.getChildByName(item.father);
                        if(father){
                            relWidth = father.getBounds().width;
                            relHeight = father.getBounds().height;
                        }
                    }
                    if(key=="y"){
                        item.proObj[key] = config.prop[key]*relHeight;
                    }else{
                        item.proObj[key] = config.prop[key]*relWidth;
                    }
                }
            }
            tween.to(item.proObj, config.during,createjs.Ease[config.ease]);
            if(config.loop){
                tween.to(item.conObj, config.during,createjs.Ease[config.ease]);
            } 
            if(config.call){
                try{
                    tween.call(eval(config.call));
                }catch(e){
                }
            }
            if(config.end){
                tween.call(function(){
                    for (var i =0; i <config.end.length; i++) {
                        switch (config.end[i].type){
                            case "jumpto":
                                var page=config.end[i].page;
                                setTimeout(function(){
                                    contentLayer.jumpTo(page);
                                },config.end[i].wait)
                                break;
                            case "runSprite":
                                var name=config.end[i]["SpriteName"];
                                setTimeout(function(){
                                    that.getChildByName(name).qiehuan();
                                    // item.qiehuan();
                                },config.end[i].wait)
                                break;
                        }
                    }
                });               
            }
        }    
    }

    /*
    *绘制页面
    * */
    p.drawPage = function(){
        // console.log(this.resItems,this.resItems.length);
        for(var i = 0 ;i<this.resItems.length;i++){
            // console.log(this.resItems,this.resItems.length)
            // alert(this.resItems.length)
            if(this.resItems[i].type == "manifest"){
                return;
            }
            // console.log(this.loader);
            // console.log(this.loader.loader.getResult(this.resItems[i].id))
            var pic = this.loader.getResult(this.resItems[i].id);
            var item;
            if (this.resItems[i]["Pages"][this.name]) {
            }else{
                continue;
            }
            
            switch(this.resItems[i]["Pages"][this.name].r_type.type){
                case "bitmap":
                    item = new createjs.Bitmap(pic);
                    break;
                case "switch":
                    var bitmap = new createjs.Bitmap(pic);
                    item = new eosi.website.BaseSwitch(bitmap,i,this);
                    break
                case "spritesheet":
                    var draw_content=this.resItems[i]["Pages"][this.name].prop["draw"];//精灵绘制配置对象
                    item = new eosi.website.BaseSpriteSheet(pic,draw_content);
                    break;
                case "baseslide":
                    item = new eosi.website.BaseSlide(pic);
                    break;
                case "button":
                    var bitmap = new createjs.Bitmap(pic);
                    item = new eosi.website.BaseButton(bitmap);
                    //item.addChild(bitmap);
                    break;
                case "class":
                alert(1);
                    var temClass = eval(this.resItems[i]["Pages"][this.name].r_type.className);
                    item = new temClass(this.resItems[i]["Pages"][this.name],this.resItems[i]["src"]);
                    //console.log(this.loader.getResult(this.resItems[i].id))
                    //item = new temClass(this.loader.getResult(this.resItems[i].id));
                    //console.log(this.resItems[i].r_type)
                    break;
                default :
                    item = new createjs.Bitmap(pic);
                    break;
            }
            // console.log(this.resItems[i].id);
            item.name = this.resItems[i].id;
            this.addChild(item);
            item.resIndex = i;
            // console.log(item,i)
            if(item.isDraw != undefined && item.isDraw != true){
                console.log(item,"has not be drawed")
                //设置触发动画属性对象
                return;
            }else{
                this.setScale(item,i);
                this.setInit(item,i);
                this.setPos(item,i);
                //animation
                this.setAnimation(item,i);
                this.setAction(item,i);
                //设置触发动画属性对象
                // console.log(this.resItems[i].Pages.page1.tweenTrigger);
                if(typeof this.resItems[i]["Pages"][this.name].tweenTrigger !=undefined){
                    item.tweenTrigger = this.resItems[i]["Pages"][this.name].tweenTrigger;
                }
                
            }



            //action

        }
        this.isDraw = true;
    }
    /*
    * 点击事件
    * */
    p.onClickItem = function(evt){
        if(evt.target.page){
            //console.log(evt.target.page)
            //window.location = "/#/"+evt.target.page;
            contentLayer.jumpTo(evt.target.page);
        }
        if(evt.target.group_id){
            popupLayer.createPopup(evt.target.group_id);
        }
        if(evt.target.url){
            window.location =evt.target.url;
        }
        if(evt.target.show_html_id){
            document.getElementById(evt.target.show_html_id).style.display="block";
        }
        if(evt.target.AssemblyName){
            Assembly.open(evt.target.AssemblyName);
        }
        if(evt.target.video_pro){
            VideoPage.click_play_read(evt.target.video_pro)
        }
        
        // 点击之后执行动画
        if (evt.target.id_list) {
            for (var i = 0; i <evt.target.id_list.length; i++) {
                this.triggerAnimation(evt.target.id_list[i])
            }
        }
    }

    /*
    * 销毁
    * */
    p.distoryPage = function(evt){
        this.off("removed",this.distoryPage,this);
        this.removeAllChildren();
        this.config=null;
        this.resIsLoaded = false;

        this.resItems=[];
        this.loader=null;
    }

    p.tick = function(evt){
        for(var i=0;i<this.children.length;i++){
            if(this.getChildAt(i).tick){
                //console.log("hastick")
                this.getChildAt(i).tick();
            }
        }
        //console.log(evt);
    }



    // add MyApp to myNameSpace
    window.eosi.website.BasePage = createjs.promote(BasePage, "Container");
//}());
}(window));





